<template>
  <div class="ranking-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <ElCard>
        <div class="header-content">
          <div class="exam-info">
            <h2>{{ examInfo?.exam_name || "考试排名" }}</h2>
            <div class="exam-meta">
              <span
                >考试时间：{{
                  formatTimeRange(examInfo?.start_time, examInfo?.end_time)
                }}</span
              >
              <span>参与人数：{{ rankings.length }}</span>
              <span v-if="rankings.length > 0"
                >平均分：{{ calculateAverageScore() }}</span
              >
            </div>
          </div>
          <div class="actions">
            <ElButton
              type="primary"
              :icon="Download"
              @click="exportRanking"
              :loading="exportLoading"
            >
              导出排名
            </ElButton>
          </div>
        </div>
      </ElCard>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <ElRow :gutter="20">
        <ElCol :span="6">
          <ElCard class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ rankings.length }}</div>
              <div class="stat-label">参与人数</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ calculateAverageScore() }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ getHighestScore() }}</div>
              <div class="stat-label">最高分</div>
            </div>
          </ElCard>
        </ElCol>
        <ElCol :span="6">
          <ElCard class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ getPassRate() }}%</div>
              <div class="stat-label">及格率</div>
            </div>
          </ElCard>
        </ElCol>
      </ElRow>
    </div>

    <!-- 排名表格 -->
    <ElCard class="ranking-table-card">
      <template #header>
        <div class="card-header">
          <span>排名列表</span>
          <div class="table-actions">
            <ElInput
              v-model="searchKeyword"
              placeholder="搜索用户名"
              :prefix-icon="Search"
              clearable
              style="width: 200px"
              @input="handleSearch"
            />
          </div>
        </div>
      </template>

      <ElTable
        :data="filteredRankings"
        :loading="loading"
        stripe
        border
        height="600"
      >
        <ElTableColumn label="排名" width="80" align="center" fixed="left">
          <template #default="{ row }">
            <div class="rank-badge" :class="getRankClass(row.rank)">
              <ElIcon v-if="row.rank <= 3" :size="16">
                <Trophy v-if="row.rank === 1" />
                <Medal v-else />
              </ElIcon>
              <span v-else>{{ row.rank }}</span>
            </div>
          </template>
        </ElTableColumn>

        <ElTableColumn
          label="用户名"
          prop="username"
          width="150"
          show-overflow-tooltip
        />

        <ElTableColumn label="分数" width="120" align="center">
          <template #default="{ row }">
            <div class="score-display">
              <span class="score">{{ row.score }}</span>
              <span class="total">/ {{ row.total_score }}</span>
            </div>
          </template>
        </ElTableColumn>

        <ElTableColumn label="正确率" width="100" align="center">
          <template #default="{ row }">
            <ElTag
              :type="getAccuracyType(row.score, row.total_score)"
              size="small"
            >
              {{ Math.round((row.score / row.total_score) * 100) }}%
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn label="提交时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.submit_time) }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="用时" width="120" align="center">
          <template #default="{ row }">
            {{ formatDuration(row.duration) }}
          </template>
        </ElTableColumn>

        <ElTableColumn label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <ElButton type="primary" size="small" @click="viewDetail(row)">
              查看详情
            </ElButton>
          </template>
        </ElTableColumn>
      </ElTable>
    </ElCard>

    <!-- 分数分布图表 -->
    <ElCard class="chart-card">
      <template #header>
        <span>分数分布</span>
      </template>
      <div class="chart-container">
        <div
          v-for="range in scoreDistribution"
          :key="range.label"
          class="distribution-item"
        >
          <div class="range-label">{{ range.label }}</div>
          <div class="range-bar">
            <div
              class="range-fill"
              :style="{ width: `${range.percentage}%` }"
            ></div>
          </div>
          <div class="range-count">{{ range.count }}人</div>
        </div>
      </div>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  reactive,
  ref,
} from 'vue';

import {
  ElButton,
  ElCard,
  ElCol,
  ElIcon,
  ElInput,
  ElMessage,
  ElRow,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';
import {
  useRoute,
  useRouter,
} from 'vue-router';

import { examApi } from '@/api/modules/exam.api';
import { useCommonStore } from '@/store/common';
import {
  Download,
  Medal,
  Search,
  Trophy,
} from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const commonStore = useCommonStore();

// 响应式数据
const loading = ref(true);
const exportLoading = ref(false);
const examInfo = ref<any>(null);
const rankings = ref<any[]>([]);
const searchKeyword = ref("");

// 设置页面标题
commonStore.header = "考试排名";

// 获取考试ID
const examId = route.params.id as string;

// 过滤后的排名数据
const filteredRankings = computed(() => {
  if (!searchKeyword.value) return rankings.value;

  return rankings.value.filter((item) =>
    item.username?.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 计算平均分
const calculateAverageScore = () => {
  if (rankings.value.length === 0) return 0;
  const total = rankings.value.reduce((sum, item) => sum + item.score, 0);
  return Math.round(total / rankings.value.length);
};

// 获取最高分
const getHighestScore = () => {
  if (rankings.value.length === 0) return 0;
  return Math.max(...rankings.value.map((item) => item.score));
};

// 计算及格率
const getPassRate = () => {
  if (rankings.value.length === 0) return 0;
  const passCount = rankings.value.filter((item) => {
    const percentage = (item.score / item.total_score) * 100;
    return percentage >= 60;
  }).length;
  return Math.round((passCount / rankings.value.length) * 100);
};

// 分数分布
const scoreDistribution = computed(() => {
  if (rankings.value.length === 0) return [];

  const ranges = [
    { label: "90-100分", min: 90, max: 100 },
    { label: "80-89分", min: 80, max: 89 },
    { label: "70-79分", min: 70, max: 79 },
    { label: "60-69分", min: 60, max: 69 },
    { label: "60分以下", min: 0, max: 59 },
  ];

  const maxCount = Math.max(
    ...ranges.map((range) => {
      return rankings.value.filter((item) => {
        const percentage = (item.score / item.total_score) * 100;
        return percentage >= range.min && percentage <= range.max;
      }).length;
    }),
    1
  );

  return ranges.map((range) => {
    const count = rankings.value.filter((item) => {
      const percentage = (item.score / item.total_score) * 100;
      return percentage >= range.min && percentage <= range.max;
    }).length;

    return {
      ...range,
      count,
      percentage: maxCount > 0 ? (count / maxCount) * 100 : 0,
    };
  });
});

// 获取排名样式
const getRankClass = (rank: number) => {
  if (rank === 1) return "rank-first";
  if (rank === 2) return "rank-second";
  if (rank === 3) return "rank-third";
  return "rank-normal";
};

// 获取正确率标签类型
const getAccuracyType = (score: number, totalScore: number) => {
  const percentage = (score / totalScore) * 100;
  if (percentage >= 90) return "success";
  if (percentage >= 80) return "primary";
  if (percentage >= 60) return "warning";
  return "danger";
};

// 格式化时间范围
const formatTimeRange = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) return "未知时间";

  const start = new Date(startTime);
  const end = new Date(endTime);

  const formatDateTime = (date: Date) => {
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return `${formatDateTime(start)} ~ ${formatDateTime(end)}`;
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "未知时间";

  return new Date(dateTime).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 格式化持续时间
const formatDuration = (seconds: number) => {
  if (!seconds || seconds < 0) return "0分0秒";

  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  if (hours > 0) {
    return `${hours}小时${minutes}分${secs}秒`;
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`;
  } else {
    return `${secs}秒`;
  }
};

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过computed属性实现
};

// 查看考试记录详情
const viewDetail = (row: any) => {
  // 跳转到考试记录详情页面
  router.push(`/exam-record/detail/${row.record_id}`);
};

// 导出排名
const exportRanking = async () => {
  exportLoading.value = true;
  try {
    // 这里可以实现导出功能
    ElMessage.success("导出功能待实现");
  } catch (error) {
    ElMessage.error("导出失败");
  } finally {
    exportLoading.value = false;
  }
};

// 获取数据
const fetchData = async () => {
  if (!examId) {
    ElMessage.error("考试ID不存在");
    router.back();
    return;
  }

  try {
    loading.value = true;

    // 获取考试信息
    const examResponse = await examApi.getExamDetail(examId);
    examInfo.value = examResponse.data;

    // 获取排名数据
    const rankingResponse = await examApi.getExamRanking(examId);
    rankings.value = rankingResponse.data.rankings || [];

    console.log("排名数据:", {
      exam: examInfo.value,
      rankings: rankings.value,
    });
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取排名数据失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.ranking-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
}

.exam-meta {
  display: flex;
  gap: 20px;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.ranking-table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
}

.rank-first {
  background: linear-gradient(45deg, #ffd700, #ffed4e);
  color: #333;
}

.rank-second {
  background: linear-gradient(45deg, #c0c0c0, #e0e0e0);
  color: #333;
}

.rank-third {
  background: linear-gradient(45deg, #cd7f32, #d4985a);
  color: #fff;
}

.rank-normal {
  background: #f5f7fa;
  color: #606266;
}

.score-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 2px;
}

.score {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.total {
  font-size: 14px;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  padding: 20px;
}

.distribution-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.distribution-item:last-child {
  margin-bottom: 0;
}

.range-label {
  width: 100px;
  font-size: 14px;
  color: #606266;
}

.range-bar {
  flex: 1;
  height: 20px;
  background-color: #f5f7fa;
  border-radius: 10px;
  overflow: hidden;
  margin: 0 15px;
}

.range-fill {
  height: 100%;
  background: linear-gradient(90deg, #409eff, #79bbff);
  border-radius: 10px;
  transition: width 0.3s ease;
}

.range-count {
  width: 60px;
  text-align: right;
  font-size: 14px;
  color: #909399;
}
</style>
